package com.qike.duola.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qike.duola.domain.*;
import com.qike.duola.dto.AddFollowListDto;
import com.qike.duola.dto.CustomerAddDto;
import com.qike.duola.dto.CustomerEditDto;
import com.qike.duola.dto.CustomerListDto;
import com.qike.duola.enums.*;
import com.qike.duola.mapper.*;
import com.qike.duola.service.DuolaContractService;
import com.qike.duola.service.DuolaCustomerService;
import com.qike.duola.utils.TimeTool;
import com.qike.duola.vo.*;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Eric.zhou
 * @Date: 2020/8/31 15:55
 */
@Service
public class DuolaCustomerServiceImpl implements DuolaCustomerService {

    private static final Logger logger = LoggerFactory.getLogger(DuolaCustomerServiceImpl.class);
    @Autowired
    private DuolaCustomerMapper duolaCustomerMapper;
    @Autowired
    private DuolaContractMapper duolaContractMapper;
    @Autowired
    private DuolaCustomerFollowMapper duolaCustomerFollowMapper;
    @Autowired
    private DuolaContractService duolaContractService;
    @Autowired
    private DuolaProjectMapper duolaProjectMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private DuolaQuoteMapper duolaQuoteMapper;


    /**
     * 添加客户
     *
     * @param customerAddDto
     */
    @Override
    public Integer customerAdd(CustomerAddDto customerAddDto) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"添加客户"+ JSON.toJSON(customerAddDto));
        DuolaCustomer duolaCustomer1 = duolaCustomerMapper.selectByName(customerAddDto.getName());
        if (duolaCustomer1!=null){
            throw new Exception(ErrorEnums.SAME_CUSTOMER.getEmsg());
        }
        DuolaCustomer duolaCustomer = new DuolaCustomer();
        duolaCustomer.setAddTime(LocalDateTime.now());
        duolaCustomer.setAddUid(userId);
        duolaCustomer.setCustomerName(customerAddDto.getName());
        duolaCustomer.setCustomerShortName(customerAddDto.getShortName());
        duolaCustomer.setContractName(customerAddDto.getContractName());
        duolaCustomer.setContractPhone(customerAddDto.getContractPhone());
        duolaCustomer.setBusinessLicense(customerAddDto.getBusinessLicense());
        duolaCustomer.setTaxNum(customerAddDto.getTaxNum());
        duolaCustomer.setAddress(customerAddDto.getAddress());
        duolaCustomer.setBankNum(customerAddDto.getBankNum());
        duolaCustomer.setCustomerStatus(customerAddDto.getCustomerStatus());
        duolaCustomer.setLegalPerson(customerAddDto.getLegalPerson());
        duolaCustomer.setCustomerLevel(customerAddDto.getCustomerLevel());
        duolaCustomer.setCompanyType(customerAddDto.getCompanyType());
        duolaCustomer.setPhoto(customerAddDto.getPhoto());
        duolaCustomer.setStatus(StatusEnums.NO.getEcode());
        duolaCustomer.setExamineStatus(KnowledgeTypeEnums.APPROVAL.getEcode());
        duolaCustomerMapper.insertSelective(duolaCustomer);
        //todo 添加客户账号
        SysUserWithBLOBs sysUser = new SysUserWithBLOBs();
        sysUser.setAddress(customerAddDto.getAddress());
        sysUser.setUserName(customerAddDto.getName());
        sysUser.setPassword("e10adc3949ba59abbe56e057f20f883e");
        sysUser.setStatus(StatusEnums.NO.getEcode());
        sysUser.setMobilePhone(customerAddDto.getContractPhone());
        sysUser.setNickname(customerAddDto.getContractName());
        sysUser.setCreateAt(LocalDateTime.now());
        sysUser.setCreateBy(userId);
        sysUser.setPlatId(2);
        sysUserMapper.insertSelective(sysUser);
        return duolaCustomer.getId();


    }

    /**
     * 编辑客户
     *
     * @param customerEditDto
     */
    @Override
    public void customerEdit(CustomerEditDto customerEditDto) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"编辑客户"+ JSON.toJSON(customerEditDto));
        DuolaCustomer duolaCustomer = duolaCustomerMapper.selectByPrimaryKey(customerEditDto.getId());
        if (duolaCustomer==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        duolaCustomer.setAddTime(LocalDateTime.now());
        duolaCustomer.setAddUid(userId);
        duolaCustomer.setCustomerName(customerEditDto.getName());
        duolaCustomer.setCustomerShortName(customerEditDto.getShortName());
        duolaCustomer.setContractName(customerEditDto.getContractName());
        duolaCustomer.setContractPhone(customerEditDto.getContractPhone());
        duolaCustomer.setBusinessLicense(customerEditDto.getBusinessLicense());
        duolaCustomer.setTaxNum(customerEditDto.getTaxNum());
        duolaCustomer.setAddress(customerEditDto.getAddress());
        duolaCustomer.setBankNum(customerEditDto.getBankNum());
        duolaCustomer.setCustomerStatus(customerEditDto.getCustomerStatus());
        duolaCustomer.setLegalPerson(customerEditDto.getLegalPerson());
        duolaCustomer.setCustomerLevel(customerEditDto.getCustomerLevel());
        duolaCustomer.setCompanyType(customerEditDto.getCompanyType());
        duolaCustomer.setPhoto(customerEditDto.getPhoto());
        duolaCustomer.setStatus(StatusEnums.NO.getEcode());
        duolaCustomer.setExamineStatus(KnowledgeTypeEnums.APPROVAL.getEcode());
        duolaCustomerMapper.updateByPrimaryKeyWithBLOBs(duolaCustomer);

    }

    /**
     * 客户列表
     *
     * @param customerListDto
     * @return
     */
    @Override
    public CustomerListVo customerList(CustomerListDto customerListDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"客户列表"+ JSON.toJSON(customerListDto));
        CustomerListVo vo = new CustomerListVo();
        List<CustomerVo> list = new ArrayList<>();

        DuolaCustomerExample customerExample = new DuolaCustomerExample();
        DuolaCustomerExample.Criteria criteria = customerExample.createCriteria();
        //客户姓名 简称
        if (!StringUtils.isEmpty(customerListDto.getName())){
            customerExample.or().andCustomerNameLike(customerListDto.getName());
            customerExample.or().andCustomerShortNameLike(customerListDto.getName());
//            criteria.andCustomerNameEqualTo(customerListDto.getName());
        }
        //联系人
        if (!StringUtils.isEmpty(customerListDto.getContractName())){
            criteria.andContractNameEqualTo(customerListDto.getContractName());
        }
        //客户评级
        if (!StringUtils.isEmpty(customerListDto.getCustomerLevel())){
            criteria.andCustomerLevelEqualTo(customerListDto.getCustomerLevel());
        }
        //联系电话
        if (!StringUtils.isEmpty(customerListDto.getContractPhone())){
            criteria.andContractPhoneEqualTo(customerListDto.getContractPhone());
        }
        //客户状态
        if (!StringUtils.isEmpty(customerListDto.getCustomerStatus())){
            criteria.andCustomerStatusEqualTo(customerListDto.getCustomerStatus());
        }
        customerExample.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(customerListDto.getStartPage(), customerListDto.getPageSize());
        List<DuolaCustomer> duolaCustomers = duolaCustomerMapper.selectByExampleWithBLOBs(customerExample);
        for (DuolaCustomer duolaCustomer : duolaCustomers) {
            CustomerVo customerVo = new CustomerVo();
            customerVo.setId(duolaCustomer.getId());
            customerVo.setAddress(duolaCustomer.getAddress());
            customerVo.setContractName(duolaCustomer.getContractName());
            customerVo.setAddTime(TimeTool.LocalDateTimeFormat(duolaCustomer.getAddTime()));
            customerVo.setContractPhone(duolaCustomer.getContractPhone());
            customerVo.setContractName(duolaCustomer.getContractName());
            customerVo.setCustomerLevel(duolaCustomer.getCustomerLevel());
            if (duolaCustomer.getCustomerStatus()!=null){
                customerVo.setCustomerStatusStr(CustomerStatusEnums.statOf(duolaCustomer.getCustomerStatus()).getEmsg());
            }
            if (duolaCustomer.getCompanyType()!=null){
                customerVo.setCompanyTypeStr(CompanyTypeEnums.statOf(duolaCustomer.getCompanyType()).getEmsg());
            }
            customerVo.setName(duolaCustomer.getCustomerName());
            customerVo.setFollowTime(duolaCustomer.getCustomerName());
            list.add(customerVo);
        }
        vo.setList(list);
        vo.setTotal(page.getTotal());
        return vo;
    }

    /**
     * 客户详情
     *
     * @param id
     * @return
     */
    @Override
    public CustomerInfoVo customerInfo(Integer id) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"客户详情"+ JSON.toJSON(id));
        DuolaCustomer duolaCustomer = duolaCustomerMapper.selectByPrimaryKey(id);
        if (duolaCustomer==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        CustomerInfoVo vo = new CustomerInfoVo();
        vo.setName(duolaCustomer.getCustomerName());
        vo.setContractName(duolaCustomer.getContractName());
        vo.setContractPhone(duolaCustomer.getContractPhone());
        vo.setCustomerStatus(duolaCustomer.getCustomerStatus());
        if (duolaCustomer.getCustomerStatus()!=null){
            vo.setCustomerStatusStr(CustomerStatusEnums.statOf(duolaCustomer.getCustomerStatus()).getEmsg());
        }
        vo.setCustomerLevel(duolaCustomer.getCustomerLevel());
        vo.setShortName(duolaCustomer.getCustomerShortName());
        vo.setBusinessLicense(duolaCustomer.getBusinessLicense());
        vo.setTaxNum(duolaCustomer.getTaxNum());
        vo.setBankNum(duolaCustomer.getBankNum());
        vo.setAddress(duolaCustomer.getAddress());
        vo.setLegalPerson(duolaCustomer.getLegalPerson());
        vo.setCompanyType(duolaCustomer.getCompanyType());
        if (duolaCustomer.getCompanyType()!=null){
            vo.setCompanyTypeStr(CompanyTypeEnums.statOf(duolaCustomer.getCompanyType()).getEmsg());
        }
        vo.setPhoto(duolaCustomer.getPhoto());
        //合同列表
        List<ContractList> list = new ArrayList<>();
        DuolaContractExample example = new DuolaContractExample();
        DuolaContractExample.Criteria criteria = example.createCriteria();
        //客户id
        criteria.andCustomerIdEqualTo(id);
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode()).andParentIdIsNull();
        List<DuolaContractWithBLOBs> duolaContractWithBLOBs = duolaContractMapper.selectByExampleWithBLOBs(example);
        for (DuolaContractWithBLOBs duolaContractWithBLOB : duolaContractWithBLOBs) {
            duolaContractService.integrationContractList(duolaContractWithBLOB, list);
        }
        //报价单列表
        List<QuoteList> quoteLists = new ArrayList<>();
        DuolaQuoteExample duolaQuoteExample = new DuolaQuoteExample();
        DuolaQuoteExample.Criteria duolaQuoteCriteria = duolaQuoteExample.createCriteria();
        duolaQuoteCriteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        //客户查询
        duolaQuoteCriteria.andCustomerIdEqualTo(id);
        //查询所有工程
        Map<Integer, String> ProjectMap = new HashMap<>();
        DuolaProjectExample projectExample = new DuolaProjectExample();
        projectExample.createCriteria().andCustomerIdEqualTo(id);
        List<DuolaProject> duolaProjects = duolaProjectMapper.selectByExample(projectExample);
        for (DuolaProject duolaProject : duolaProjects) {
            ProjectMap.put(duolaProject.getId(), duolaProject.getProjectName());
        }
        //查询所有人员
        Map<Long, String> userMap = new HashMap<>();
        List<SysUser> sysUsers = sysUserMapper.selectByExample(new SysUserExample());
        for (SysUser sysUser : sysUsers) {
            userMap.put(sysUser.getId(), sysUser.getNickname());
        }
        duolaQuoteExample.setOrderByClause("add_time desc");
        List<DuolaQuote> duolaQuotes = duolaQuoteMapper.selectByExample(duolaQuoteExample);
        for (DuolaQuote duolaQuote : duolaQuotes) {
            QuoteList quoteList = new QuoteList();
            quoteList.setTitle(duolaQuote.getTitle());
            quoteList.setAddTime(duolaQuote.getAddTime().toString());
            quoteList.setContractId(duolaQuote.getContractId());
            quoteList.setCustomerName(duolaQuote.getContractName());
            quoteList.setPhone(duolaQuote.getContractPhone());
            String s = ProjectMap.get(duolaQuote.getProjectId());
            quoteList.setProjectName(s);
            quoteList.setQuoteNum(duolaQuote.getQuoteNum());
            quoteList.setCustomerName(duolaCustomer.getCustomerName());
            quoteList.setContactName(duolaQuote.getContractName());
            quoteList.setTime(duolaQuote.getStartTime().toString() + "-" + duolaQuote.getEndTime().toString());
            String s2 = userMap.get(duolaQuote.getSaleId());
            quoteList.setSaleName(s2);
            quoteList.setId(duolaQuote.getId());
            quoteList.setRemark(duolaQuote.getRemark());
            quoteList.setExamineStatus(duolaQuote.getExamineStatus());
            quoteList.setExamineStatusStr(ExamineEnums.statOf(duolaQuote.getExamineStatus()).getEmsg());
            quoteList.setContractId(duolaQuote.getContractId());
            quoteLists.add(quoteList);
        }

        //todo 工程列表
        List<ProjectList> projectLists = new ArrayList<>();
        DuolaProjectExample.Criteria projectCriteria = projectExample.createCriteria();
        projectCriteria.andCustomerIdEqualTo(id);
        projectExample.setOrderByClause("add_time desc");
        for (DuolaProject duolaProject : duolaProjects) {
            ProjectList projectList = new ProjectList();
            projectList.setAddress(duolaProject.getProjectAddress());
            projectList.setRemark(duolaProject.getRemark());
            projectList.setName(duolaProject.getContractName());
            projectList.setProjectNum(duolaProject.getProjectNum());
            projectList.setPhone(duolaProject.getContractPhone());
            projectList.setCustomerName(duolaCustomer.getCustomerName());
            projectList.setProjectName(duolaProject.getProjectName());
            projectList.setDistance(duolaProject.getDistance());
            projectList.setAddTime(duolaProject.getAddTime().toString());
            projectList.setExaminStr(ExamineEnums.statOf(duolaProject.getExamineStatus()).getEmsg());
            projectList.setId(duolaProject.getId());
            projectLists.add(projectList);
        }
        vo.setProjectist(projectLists);
        vo.setContractList(list);
        vo.setQuoteList(quoteLists);
        return vo;
    }

    /**
     * 跟进记录
     *
     * @param id
     * @return
     */
    @Override
    public FollowListVo followList(Integer id) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"跟进记录"+ JSON.toJSON(id));
        DuolaCustomer duolaCustomer = duolaCustomerMapper.selectByPrimaryKey(id);
        if (duolaCustomer==null){
            throw new Exception(ErrorEnums.ERROR_DATA.getEmsg());
        }
        FollowListVo vo = new FollowListVo();
        vo.setName(duolaCustomer.getCustomerName());
        vo.setAddress(duolaCustomer.getAddress());
        vo.setContractPhone(duolaCustomer.getContractPhone());
        vo.setCustomerLevel(duolaCustomer.getCustomerLevel());
        vo.setCustomerStatus(duolaCustomer.getCustomerStatus());
        if (duolaCustomer.getCustomerStatus()!=null){
            vo.setCustomerStatusStr(CustomerStatusEnums.statOf(duolaCustomer.getCustomerStatus()).getEmsg());
        }
        List<FollowList> list = new ArrayList<>();
        DuolaCustomerFollowExample example= new DuolaCustomerFollowExample();
        example.createCriteria().andCustomerIdEqualTo(id);
        example.setOrderByClause("add_time desc");
        List<DuolaCustomerFollow> duolaCustomerFollows = duolaCustomerFollowMapper.selectByExample(example);
        for (DuolaCustomerFollow duolaCustomerFollow : duolaCustomerFollows) {
            FollowList followList = new FollowList();
            followList.setId(duolaCustomerFollow.getId());
            followList.setAddTime(TimeTool.LocalDateTimeFormat(duolaCustomerFollow.getAddTime()));
            followList.setCustomerStatusStr(CustomerStatusEnums.statOf(duolaCustomerFollow.getCustomerStatus()).getEmsg());
            followList.setCustomerStatus(duolaCustomerFollow.getCustomerStatus());
            followList.setRemark(duolaCustomerFollow.getRemark());
            list.add(followList);
        }
        vo.setList(list);
        return vo;
    }

    /**
     * 添加跟进记录
     *
     * @param addFollowListDto
     */
    @Override
    public void addFollowList(AddFollowListDto addFollowListDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"添加跟进记录"+ JSON.toJSON(addFollowListDto));
        DuolaCustomerFollow customerFollow = new DuolaCustomerFollow();
        customerFollow.setAddTime(LocalDateTime.now());
        customerFollow.setAddUid(userId);
        customerFollow.setRemark(addFollowListDto.getRemark());
        customerFollow.setCustomerId(addFollowListDto.getCustomerId());
        customerFollow.setCustomerStatus(addFollowListDto.getCustomerStatus());
        duolaCustomerFollowMapper.insertSelective(customerFollow);
        DuolaCustomer duolaCustomer = duolaCustomerMapper.selectByPrimaryKey(addFollowListDto.getCustomerId());
        duolaCustomer.setCustomerStatus(addFollowListDto.getCustomerStatus());
        duolaCustomer.setUpdateUid(userId);
        duolaCustomer.setUpdateTime(LocalDateTime.now());
        duolaCustomerMapper.updateByPrimaryKeySelective(duolaCustomer);
    }

    /**
     * 客户名称下拉列表
     *
     * @param name
     * @return
     */
    @Override
    public List<EnumList> customerPullList(String name) {
        List<EnumList> list = new ArrayList<>();
        DuolaCustomerExample example  = new DuolaCustomerExample();
        if (!StringUtils.isEmpty(name)){
            example.createCriteria().andCustomerNameLike(name);
        }
        List<DuolaCustomer> duolaCustomers = duolaCustomerMapper.selectByExample(example);
        for (DuolaCustomer duolaCustomer : duolaCustomers) {
            EnumList enumList = new EnumList();
            enumList.setKey(duolaCustomer.getId());
            enumList.setValue(duolaCustomer.getCustomerName());
            list.add(enumList);
        }
        return list;
    }

    /**
     * 联系人下拉列表
     *
     * @param name
     * @return
     */
    @Override
    public List<EnumList> contractPullList(String name) {
        List<EnumList> list = new ArrayList<>();
        DuolaCustomerExample example  = new DuolaCustomerExample();
        if (!StringUtils.isEmpty(name)){
            example.createCriteria().andContractNameLike(name);
        }
        List<DuolaCustomer> duolaCustomers = duolaCustomerMapper.selectByExample(example);
        for (DuolaCustomer duolaCustomer : duolaCustomers) {
            EnumList enumList = new EnumList();
            enumList.setKey(duolaCustomer.getId());
            enumList.setValue(duolaCustomer.getContractName());
            list.add(enumList);
        }
        return list;
    }
}
